<template>
  <el-select
    v-model="value"
    :loading="loading"
    @change="tenantChange"
    reserve-keyword
    remote
    filterable
    placeholder="请输入租户编码搜索"
    :remote-method="initMember"
    @focus="initMember('all')"
    class="select"
    clearable
  >
    <el-option
      v-for="item in options"
      :key="item.id"
      :label="item.tenantName"
      :value="item.id"
    >
      <span>{{ item.tenantName }} - {{ item.tenantCode }}</span>
    </el-option>
  </el-select>
</template>

<script>
import { page } from '@/api/system/sys/tenant'
/**
 * 租户下拉组件
 */
export default {
  name: 'TenantSearch',
  props: {
    tenantId: {
      type: String,
      default: undefined
    }
  },
  data() {
    return {
      // 租户下拉列表集合
      options: [],
      // 加载等待状态
      loading: false,
      // 租户id
      value: undefined
    }
  },
  watch: {
    defaultValue: {
      handler(newValue, oldValue) {
        if (newValue !== oldValue) {
          this.value = newValue
        }
      }
    }
  },
  created() {
    this.value = this.tenantId
    this.initMember('all')
  },
  methods: {
    initMember(v) {
      if (v) {
        this.loading = true
        const params = { tenant_code: v === 'all' ? undefined : v }
        page(params).then((res) => {
          const { data } = res
          if (data.rows) {
            this.options = data.rows
            this.loading = false
          }
        })
      } else {
        this.options = []
      }
    },
    /**
     * 选中租户后回调
     */
    tenantChange() {
      let tenant = {}
      this.options.map((item) => {
        if (this.value === item.id) {
          tenant = item
        }
      })
      this.$emit('onChange', tenant)
    }
  }
}
</script>

<style lang="scss" scoped >
.select {
  width: 100%;
}
</style>
